<template>
  <!-- 工具库 -->
  <div>
    <div class="title_info">
      <div class="project">项目阶段</div>
      <search
        class="m-l20"
        ref="tableRef"
        :fields="state.fields"
        @searchList="searchList"
        @resetList="resetList"
        style="flex: 1"
      ></search>
      <el-button class="button_edit" @click="onUpload">上传资料</el-button>
    </div>

    <div class="main_sty">
      <div class="tree_sty">
        <el-tree
          v-if="state.data.length"
          :data="state.data"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ data }">
            <span class="custom-tree-node">
              <!-- <span>{{ data.departmentName }}</span> -->
              <span>{{ data["stageName"] }}</span>
            </span>
            <span
              class="custom-tree-node-show"
              v-if="projectStageId == data['projectStageId']"
            >
              <CaretRight
                style="
                  width: 1em;
                  height: 1em;
                  margin-right: 8px;
                  color: #fc7018;
                "
              ></CaretRight>
            </span>
          </template>
        </el-tree>
        <el-empty v-else description="暂无数据" />
      </div>

      <div class="list-box">
        <div>
          <div style="padding-left: 15px; margin-bottom: 10px">
            <el-switch
              v-model="isActive"
              active-text="卡片"
              inactive-text="列表"
            />
          </div>
        </div>
        <div class="research_report">
          <div v-if="isActive" class="research_report">
            <div class="zanwu" v-if="state.filePageList.length == 0">
              <el-empty description="暂无数据" />
            </div>
            <el-card
              class="box-card"
              v-for="(v, i) in state.filePageList"
              :key="i"
            >
              <div class="title">{{ v.fileName || "暂无" }}</div>
              <div class="department">
                <div>
                  <svg-icon icon-class="department-icon" class="m-r5" />
                  {{ v.departmentName }}
                </div>
                <div>
                  <svg-icon icon-class="user-icon" class="m-r5" />
                  {{ v.userName }}
                </div>
              </div>
              <div class="time">
                <svg-icon icon-class="date-icon" class="m-r5" />
                <span style="color: #b3b3b3">{{
                  v.createTime || "0000-00-00"
                }}</span>
              </div>
              <el-divider></el-divider>
              <div class="people">
                <div class="donwloadAll">{{ v.downloadNum }}人已下载</div>
                <div class="svg_sty d-flex a-center">
                  <svg-icon
                    class="mgl mgr"
                    @click="viewDocument(v)"
                    icon-class="view_icon"
                    style="font-size: 18px; font-weight: 600"
                  />
                  <svg-icon
                    class="mgr"
                    @click="updataHandel(v)"
                    icon-class="download-icon"
                  />
                  <svg-icon
                    class="mgr"
                    @click="deleteHandel(v)"
                    icon-class="delete-icon"
                  />
                </div>
              </div>
            </el-card>
          </div>
          <div class="table-list-content" v-else>
            <public-table
              height="550px"
              :table-data="state.filePageList"
              :table-option="tableOption"
              :page="pageParam"
              :is-paging="false"
            >
              <template #operate="{ row }">
                <div class="operate d-flex a-center">
                  <svg-icon
                    class="m-r10"
                    @click="viewDocument(row)"
                    icon-class="view_icon"
                    style="font-size: 18px; font-weight: 600"
                  />
                  <svg-icon
                    class="m-r10"
                    @click="updataHandel(row)"
                    icon-class="download-icon"
                  />
                  <svg-icon
                    class="mgr"
                    @click="deleteHandel(row)"
                    icon-class="delete-icon"
                  />
                </div>
              </template>
            </public-table>
          </div>
        </div>
      </div>

      <div class="operation_record">
        <blockComponents :msg="'操作记录'"></blockComponents>
        <div class="record-box">
          <div class="zanwu" v-if="state.downloadLogList.length == 0">
            <el-empty description="暂无数据" />
          </div>
          <template v-else>
            <div
              class="operation d-flex"
              v-for="(item, index) in state.downloadLogList"
              :key="index"
            >
              <div class="img_sty m-r5">
                <img src="@/assets/iconImg/zujin.png" alt="" />
              </div>
              <div class="text">
                <div>
                  <span class="font_sty">{{ item.userName }}</span>
                  <span class="px-10" style="color: #666666">{{
                    ["", "上传", "下载", "删除"][item.type] || "下载"
                  }}</span>
                  <a class="font_sty" href="#">{{ item.fileName }}</a>
                </div>
                <div class="time">
                  <svg-icon icon-class="date-icon" />
                  {{ item.operateTime || item.createTime }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>

  <!-- 上传资料   -->
  <public-dialog
    :title="'上传项目资料'"
    :width="'40%'"
    :confirmButtonTitle="'确认'"
    v-model:visible="visible"
    @onConfirm="onConfirm"
  >
    <div class="public-dialog-content d-flex flex-column">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        action="#"
        limit="1"
        :http-request="uploadFile"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处或<em>点击上传</em></div>
      </el-upload>
    </div>
  </public-dialog>
</template>
<script setup>
import {
  ElTree,
  ElCard,
  ElEmpty,
  ElDivider,
  ElUpload,
  ElLoading,
  ElMessage,
  ElSwitch,
} from "element-plus";
import "@/views/constructionProjectManage/static/button.scss";
import Search from "@/components/table/search.vue";
import { CaretRight, UploadFilled } from "@element-plus/icons-vue";
import BlockComponents from "@/components/block_components/index.vue";

import {
  toolApi,
  reserveInvestmentProjectLibraryApi,
  projectFileApi,
  fileApi,
} from "@/api/investment.js";
import { getURLhandler } from "@/common/utils/GlobalUtils";
import { reactive, ref, onMounted, onBeforeMount, watch, nextTick } from "vue";

import { useRouter, useRoute } from "vue-router";
import PublicDialog from "@/components/PublicDialog.vue";
import { retirementApi } from "@/api/businessFinance";
import axios from "axios";
import PublicTable from "@/components/PublicTable.vue";
import { fileTypeMap, exportToFile } from "@/hooks/useCommon";
const router = useRouter();
let route = useRoute();

const uploadRef = ref(null);

const isActive = ref(true);

let projectId = getURLhandler(route.path).projectId;
let projectTypeId = getURLhandler(route.path).projectTypeId;

const state = reactive({
  data: [],
  fields: [
    {
      key: "keywords",
      label: "文件名称关键字",
      type: "input",
      placeholder: "请输入关键字",
    },
    { key: "startTime-endTime", label: "上传时间", type: "datetimerange" },
  ],
  downloadLogList: [],
  filePageList: [],
});

const tableOption = reactive([
  {
    label: "文件名称",
    prop: "fileName",
    overHidden: false,
    minWidth: 300,
  },
  {
    label: "上传人",
    prop: "userName",
    minWidth: 50,
  },
  {
    label: "上传时间",
    prop: "createTime",
    minWidth: 80,
  },
  {
    label: "操作",
    prop: "operate",
    minWidth: 80,
    slot: true,
  },
]);

let pageParam = reactive({
  total: 0,
  current: 1,
  size: 20,
});

/**
 * 查看文档
 */
const viewDocument = (row) => {
  let httpUrl = `http://116.169.61.207:12008/gxsst/`;
  let url = row.fileUrlKey;
  let fileUrl = url.split("/");
  let fileUrlKey = fileUrl[fileUrl.length - 1];
  let fileUrlKeyArr = fileUrlKey.split(".");
  let fileUrlKeySuffix = fileUrlKeyArr[fileUrlKeyArr.length - 1];

  let obj = {
    pdf: "pdf",
    docx: "docx",
    xlsx: "xlsx",
    xls: "xls",
    png: "png",
    jpg: "jpg",
    jpeg: "jpeg",
  };
  if (!obj[fileUrlKeySuffix]) {
    return ElMessage.error("暂不支持该文件格式预览");
  }

  let key = url.replaceAll("/", "@");
  if (fileUrlKeySuffix === "pdf") {
    window.open(`/document/pdf/${key}`, "_blank");
  }
  if (fileUrlKeySuffix === "docx") {
    window.open(`/document/docx/${key}`, "_blank");
  }
  if (fileUrlKeySuffix === "xlsx" || fileUrlKeySuffix === "xls") {
    window.open(`/document/xlsx/${key}`, "_blank");
  }
  if (
    fileUrlKeySuffix === "png" ||
    fileUrlKeySuffix === "jpg" ||
    fileUrlKeySuffix === "jpeg"
  ) {
    // window.open('','','width=500,height=300,top=100,left=600').document.write(`<!DOCTYPE html><html><body ><img src='${httpUrl+url}'/></body></html>`)
    window
      .open("", "_blank")
      .document.write(
        `<!DOCTYPE html><html lang=""><body ><img src='${
          httpUrl + url
        }' alt=""/></body></html>`
      );
  }
};

const getCogList = () => {
  projectFileApi
    .getDownloadLogList({
      projectStageId: projectStageId.value || "",
      projectId: projectId,
    })
    .then((res) => {
      if (res.code === "200") {
        state.downloadLogList = res.data;
      }
    });
};

const tableRef = ref(null);
const projectStageId = ref(null);
const handleNodeClick = (data) => {
  projectStageId.value = data.projectStageId || "";
  const obj = {
    ...tableRef.value.getSearchParams(),
  };
  getFilePageList(obj);
  getCogList();
};

const searchList = (e) => {
  getFilePageList(e);
};
const resetList = (e) => {
  projectStageId.value = "";
  getFilePageList();
  getCogList();
};

const getFilePageList = (param) => {
  projectFileApi
    .getFilePageList({
      pageNum: 1,
      pageSize: 99999,
      param: {
        ...param,
        projectStageId: projectStageId.value,
        projectId,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        state.filePageList = res.data.content;
      }
    });
};

const updataHandel = (item) => {
  projectFileApi
    .download({
      urlKey: item.fileUrlKey,
      stageId: projectStageId.value,
    })
    .then((res) => {
      exportToFile(res.data, item.fileName);

      // let blob = new Blob([res], {
      // 	type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      // });
      // let a = document.createElement("a");
      // a.href = URL.createObjectURL(blob);
      // a.download = item.fileName;
      // a.click();
      // URL.revokeObjectURL(a.href);
      // a.remove();
      getFilePageList();
      getCogList();
    });
};

const deleteHandel = (item) => {
  console.log("item", item);
  /*toolApi
		.toolDelete({
			urlKey: item.fileUrlKey,
			catId: item.projectStageId,
		})
		.then((res) => {
			if (res.code === '200') {
				ElMessage.success("删除成功");
				getFilePageList();
			}
		});*/

  toolApi
    .toolDelete2({
      urlKey: item.fileUrlKey,
    })
    .then((res) => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        getFilePageList();
      }
    });
};

//获取项目类型
const getCatList = () => {
  reserveInvestmentProjectLibraryApi
    .getStage(projectId, projectTypeId)
    .then((res) => {
      if (res.code == 200) {
        state.data = res.data.stages;
        projectStageId.value = state.data[0]?.projectStageId;
        searchList();
        getCogList();
      }
    });
};

const visible = ref(false);

/**
 * 确认
 */
const onConfirm = () => {};

/**
 * 上传按钮
 */
const onUpload = () => {
  visible.value = true;
  setTimeout(() => {
    uploadRef.value.clearFiles();
  }, 500);
};

/**
 * 上传文件
 */
const uploadFile = (file) => {
  /*const addTypeArray = file.file.name.split(".");
	const addType = addTypeArray[addTypeArray.length - 1]
	if(addType === "doc"){
		setTimeout(()=>{
			uploadRef.value.clearFiles();
		},500);
		return ElMessage.error("暂不支持doc文件格式上传,请转为docx格式后上传");
	}*/

  let resFile = file.file; //注意：直接上传file文件，不要用FormData对象的形式传
  let config = {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  };

  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  fileApi
    .getMinioAddress({ fileName: resFile.name })
    .then((res) => {
      let result = res.data.url;

      if (res.code === "200") {
        //需要用put方法上传，post会报405，aws官方规定是put方法
        axios
          .put(result, resFile, config)
          .then((resData) => {
            if (resData.status === 200) {
              projectFileApi
                .record({
                  projectId: projectId,
                  stageId: projectStageId.value,
                  fileUrl: res.data.fileUrl,
                  fileName: resFile.name,
                })
                .then((res) => {
                  if (res.code === "200") {
                    loading.close();
                    ElMessage.success("上传成功!");
                    visible.value = false;
                    getCatList();
                    uploadRef.value.clearFiles();
                    console.log("resData", resData);
                  }
                  if (res.code !== "200") {
                    loading.close();
                    visible.value = false;
                    uploadRef.value.clearFiles();
                    ElMessage.error("上传失败,请联系管理员!");
                  }
                })
                .catch((err) => {
                  console.log(err);
                  loading.close();
                  visible.value = false;
                  uploadRef.value.clearFiles();
                  ElMessage.error("上传失败,请联系管理员!");
                });
            }
            if (resData.status !== 200) {
              loading.close();
              visible.value = false;
              uploadRef.value.clearFiles();
              ElMessage.error("上传失败,请联系管理员!");
            }
          })
          .catch((err) => {
            console.log(err);
            loading.close();
            visible.value = false;
            uploadRef.value.clearFiles();
            ElMessage.error("上传失败,请联系管理员!");
          });
      }
      if (res.code !== "200") {
        loading.close();
        visible.value = false;
        uploadRef.value.clearFiles();
        ElMessage.error("上传失败,请联系管理员!");
      }
    })
    .catch((error) => {
      loading.close();
      visible.value = false;
      uploadRef.value.clearFiles();
      ElMessage.error("上传失败,请联系管理员!");
    });
};

onMounted(() => {
  getCatList();
});
</script>

<style lang="scss" scoped>
.projectPeople {
  color: #fff;
  cursor: pointer;

  text-align: center;
  font-size: 12px;
  height: 20px;

  line-height: 20px;
  margin-left: 20px;
  background-color: #d4ae85;
  border-radius: 10px;
  padding-left: 5px;
  padding-right: 5px;
}
.title_info {
  display: flex;
  // justify-content: space-between;
}
.main_sty {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  .tree_sty {
    width: 15%;
    .el-tree {
      border: 1px solid #e3e7f1;
      border-radius: 6px;
      padding: 15px 10px;
    }
  }
}
.project {
  width: 15%;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 6px;
  font-size: 14px;
  font-family: SourceHanSansMedium, SourceHanSansCN;
  font-weight: bold;
  color: #1a1a1a;
  border: 1px solid #e3e7f1;
}

.list-box {
  flex: 1;
}
.table-list-content {
  padding: 0 30px;
  flex: 1;
}
.research_report {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  .box-card {
    --ww: calc((100% - 30% * 3) / 3 / 2);
    width: 30%;
    margin: 0 var(--ww) 20px;
    // height: 160px;
    background: #ffffff;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.03);
    border-radius: 12px;
    border: none;
    .title {
      font-size: 17px;
      font-family: SourceHanSansMedium, SourceHanSansCN;
      color: #000000;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }

    .department,
    .people {
      margin-top: 15px;
      color: #666666;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      .donwloadAll {
        width: 200px;
      }
      .svg_sty {
        //width: 61px;
        //box-sizing: border-box;
        //svg {
        //	margin-left: 10px;
        //	cursor: pointer;
        //}

        .mgr {
          margin-right: 10px;
          cursor: pointer;
        }
      }
    }
  }
}
.operation_record {
  width: 20%;
  .record-box {
    border-radius: 12px;
    border: 1px solid #e3e7f1;
    margin-top: 10px;
  }
}
.font_sty {
  color: #d4ae85;
}
.operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-family: SourceHanSansMedium, SourceHanSansCN;
  margin: 0px 10px;
  padding: 15px 0;
  border-bottom: 1px solid #e3e7f1;
  &:last-child {
    border: none;
  }
  .text {
    width: calc(100% - 40px);
    padding-left: 10px;
  }
}
.img_sty {
  margin-top: 5px;
  width: 40px !important;
  height: 36px;
  // background-color: pink;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
.custom-tree-node-show {
  margin-left: 10px;
}
:deep(.el-cascader) {
  width: 100%;
}
.time {
  color: #666666;
  font-size: 14px;
  margin-top: 10px;
}
.zanwu {
  color: #606266;
  text-align: center;
  font-size: 14px;
  margin-top: 10px;
  width: 100%;
}

:deep(.el-divider) {
  margin: 15px 0;
}

:deep(.el-card) {
  .el-card__body {
    padding-top: 15px;
    padding-bottom: 25px;
  }
}
</style>
